﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pdfer.Filters
{
    internal class RunLengthDecodeFilter : IFilter
    {
        /// <summary>
        /// <inheritdoc/>
        /// 线程安全的
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public byte[] Decode(ReadOnlySpan<Byte> input)
        {
            using var output = new MemoryStream();
            Byte lenByte = 0;
            for (int i = 0; i < input.Length; i++) 
            {
                lenByte = input[i];
                if(lenByte == 128)
                {
                    // 128 EOD
                    break;
                }
                if(lenByte < 128)
                {
                    // 区间 [0, 127]
                    // 1 到 128个数据
                    // 把后面的(lenByte + 1)数据拷贝到输出
                    for (int j = 0; j < lenByte + 1; j++) 
                    {
                        i++;
                        if(i >= input.Length)
                        {
                            break ;
                        }
                        output.WriteByte(input[i]);
                    }
                }
                else
                {
                    // 区间 [129, 255]
                    // 下一个字节的数据重复lenByte次
                    i++;
                    if (i < input.Length)
                    {
                        var dubData = input[i];
                        var _lenByte = 257 - (lenByte & 0xFF);
                        for (int j = 0; j < _lenByte; j++)
                        {
                            output.WriteByte(dubData);
                        }
                    }
                }

            }
            return output.ToArray();
        }

        public byte[] Encode(ReadOnlySpan<Byte> input)
        {
            throw new NotImplementedException();
        }
    }
}
